<?php

namespace App\Library\Wechat;

use EasyWeChat\MiniApp\Application;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;
class WeChatApi
{
    /**
     * 微信登录获AccessToken
     *
     * @param [array] $code 通过code换取Token
     * @return void
     */
    public static function getAccessToken($code)
    {
        $wechat = getWxConfig('MiniApp');
        $app_id = $wechat['app_id'];
        $secret = $wechat['secret'];


        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' .$app_id . '&secret=' .   $secret . '&code=' . $code . '&grant_type=authorization_code';
        try {
            $client = new Client();
            $res = $client->get($url);
        } catch (RequestException $e) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错，请稍后再试。'
            ];
            return $vdata;
        }
        $body = $res->getBody();
        $getCntents = $body->getContents();
        $cntentsArr = json_decode($getCntents, true);

        if (isset($cntentsArr['errcode'])) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错，请稍后再试。',
            ];
            Log::info('微信登录失败代码：');
            Log::info($cntentsArr);
        } else {
            $vdata = [
                'code' => 20000,
                'data' => $cntentsArr,
            ];
        }
        return $vdata;
    }

    /**
     * 获取用户信息方法
     *
     * @param [string] $access_token 微信Token
     * @param [string] $openid 微信Openid
     * @return void
     */
    public static function getUserInfo($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid;
        try {
            $client = new Client();
            $res = $client->get($url);
        } catch (RequestException $e) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错，请稍后再试。'
            ];
            return $vdata;
        }


        $body = $res->getBody();
        $getCntents = $body->getContents();
        $cntentsArr = json_decode($getCntents, true);

        if (isset($cntentsArr['errcode'])) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错，请稍后再试。',
            ];
            Log::info('微信登录失败代码：');
            Log::info($cntentsArr);
        } else {
            $vdata = [
                'code' => 20000,
                'data' => $cntentsArr,
            ];
        }

        return $vdata;
    }
}
